/*
 * ide.java
 *
 * Created on Oct 29, 2008, 3:13:23 PM
 * Copyright huy
 */
package webidewar;

import com.icesoft.faces.async.render.OnDemandRenderer;
import com.icesoft.faces.async.render.RenderManager;
import com.icesoft.faces.async.render.Renderable;
import com.icesoft.faces.component.jsfcl.data.MenuBarBean;
import com.icesoft.faces.component.jsfcl.data.PopupBean;
import com.icesoft.faces.webapp.xmlhttp.PersistentFacesState;
import com.icesoft.faces.webapp.xmlhttp.RenderingException;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import org.WebIDE.ejb.entities.Files;
import org.WebIDE.ejb.entities.Projects;
import org.WebIDE.ejb.sessions.FilesFacadeRemote;
import org.WebIDE.ejb.sessions.ProjectsFacadeRemote;
import org.WebIDE.ejb.sessions.exceptions.NonexistentEntityException;
import org.WebIDE.ejb.sessions.exceptions.PreexistingEntityException;
import org.WebIDE.ejb.sessions.exceptions.RollbackFailureException;
import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import webidewar.jsf.ProjectsConverter;
import webidewar.jsf.util.JsfUtil;
import webidewar.system.*;
import webidewar.system.Process;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class ide extends AbstractPageBean implements Renderable {

    @EJB
    private ProjectsFacadeRemote projectsFacade;
    @EJB
    private FilesFacadeRemote filesFacade;
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    private int __placeholder;
    private Process p;
    private inout io;
    private String tempInput = "";
    private PersistentFacesState state = null;
    private RenderManager renderManager;
    private OnDemandRenderer personGroup = null;
    private Projects currentProject;
    private Projects newProject;
    private Files newFile;

    public Files getNewFile() {
        return newFile;
    }

    public void setNewFile(Files newFile) {
        this.newFile = newFile;
    }

    public Projects getNewProject() {
        return newProject;
    }

    public void setNewProject(Projects newProject) {
        this.newProject = newProject;
    }

    public Files getCurrentFile() {
        return currentFile;
    }

    public void setCurrentFile(Files currentFile) {
        this.currentFile = currentFile;
    }

    public Projects getCurrentProject() {
        return currentProject;
    }

    public void setCurrentProject(Projects currentProject) {
        this.currentProject = currentProject;
    }
    private Files currentFile;
    //private String code = "a = input('nhap a=')\nb = 10\nprint a + b";
    private String code = "a = input('nhap a=')\nprint(a)";

    public String getTempInput() {
        return tempInput;
    }

    public void setTempInput(String tempInput) {
        this.tempInput = tempInput;
    }

    public String getInput() {
        return io.getInput();
    }

    public void setInput(String input) {
        io.setInput(input);
    }

    public String getOutput() {
        return io.getOutput();
    }

    public void setOutput(String output) {
        io.setOutput(output);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private MenuBarBean menuBar1Bean = new MenuBarBean();

    public MenuBarBean getMenuBar1Bean() {
        return menuBar1Bean;
    }

    public void setMenuBar1Bean(MenuBarBean mbb) {
        this.menuBar1Bean = mbb;
    }
    private PopupBean panelPopup1Bean = new PopupBean();

    public PopupBean getPanelPopup1Bean() {
        return panelPopup1Bean;
    }

    public void setPanelPopup1Bean(PopupBean pb) {
        this.panelPopup1Bean = pb;
    }
    private PopupBean panelPopup2Bean = new PopupBean();

    public PopupBean getPanelPopup2Bean() {
        return panelPopup2Bean;
    }

    public void setPanelPopup2Bean(PopupBean pb) {
        this.panelPopup2Bean = pb;
    }
    private PopupBean panelPopup3Bean = new PopupBean();

    public PopupBean getPanelPopup3Bean() {
        return panelPopup3Bean;
    }

    public void setPanelPopup3Bean(PopupBean pb) {
        this.panelPopup3Bean = pb;
    }
    private PopupBean panelPopup4Bean = new PopupBean();

    public PopupBean getPanelPopup4Bean() {
        return panelPopup4Bean;
    }

    public void setPanelPopup4Bean(PopupBean pb) {
        this.panelPopup4Bean = pb;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public ide() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("ide Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
        state = PersistentFacesState.getInstance();
        io = new inout();
        newProject = new Projects();
        newFile = new Files();
        currentFile = new Files();
        panelPopup1Bean.setShowDraggablePanel(false);
        panelPopup2Bean.setShowDraggablePanel(false);
        panelPopup3Bean.setShowDraggablePanel(false);
        panelPopup4Bean.setShowDraggablePanel(false);
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    public String button1_action() {
        //return null means stay on the same page

        //setCode((String) getValue("#{Page1.code}"));
        //personGroup.requestRender();
        Thread t = new Thread(new Runnable() {

            public void run() {
                BSFManager bm = new BSFManager();

                /*  try {
                BSFEngine e = bm.loadScriptingEngine("jython");
                System.setIn(ain);
                System.setOut(new PrintStream(aou));
                e.exec("jython", 0, 0, getCode());
                } catch (BSFException ex) {
                Logger.getLogger(Page1.class.getName()).log(Level.SEVERE, null, ex);
                }
                 */
                try {
                    //System.setOut(new PrintStream(aou));
                    //code = code.replace("print ", "printx ");
                    // Logger.getLogger(Page1.class.getName()).log(Level.SEVERE,">>>>>Thread:"+code);
                    //bm.exec("jython", "", 1, 1, getCode());
                    PythonCodeModifier cm = new PythonCodeModifier();
                    cm.setId((int) Thread.currentThread().getId());

                    String newcode = cm.convert(currentFile.getContents());
                    //Logger.getLogger(Page1.class.getName()).log(Level.SEVERE, ">>>>>newcode:\n" + newcode + "\n>>>>>newcode");
                    p = new Process();
                    p.setIn(new AjaxInputStream(io, personGroup));
                    p.setOut(new AjaxOutputStream(io, personGroup));
                    p.setId((int) Thread.currentThread().getId());
                    ProcessesManager.procs.add(p);
                    //thu nghiem commit len 
                    //bm.exec("jython", "", 1, 1, "from icetest import ProcessesManager\nx = ProcessesManager()\nx.test('hello')");
                    bm.exec("jython", "", 1, 1, newcode);
                } catch (BSFException ex) {
                    //Logger.getLogger(Page1.class.getName()).log(Level.SEVERE, null, ex);
                    //Logger.getLogger(Page1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        t.start();

        //setCode("sss");
        // personGroup.requestRender();
        return null;
    }

    public PersistentFacesState getState() {
        return state;
    }

    public void renderingException(RenderingException re) {
        personGroup.remove(this);
    }

    public void setRenderManager(RenderManager renderManager) {
        if (renderManager != null) {
            this.renderManager = renderManager;
            personGroup = renderManager.getOnDemandRenderer("personGroup");
            personGroup.add(this);
        }
    }

    public RenderManager getRenderManager() {
        return renderManager;
    }

    public void inputTextarea3_processValueChange(ValueChangeEvent vce) {        //setInput(input);
        //ain.notify();
        String s = getTempInput();
        if (s.endsWith("\n")) {
            //System.out.println(">>>>>>"+getTempInput()+">>>>>>");
            //setInput(s);
            //setTempInput("");
            if (p != null) {
            }
        //personGroup.requestRender();
        }
    //if (getTempInput().length()>0)
    //if (getTempInput().endsWith("\n"))
    //System.out.println(">>>>>>"+getTempInput()+">>>>>>"+(int)getTempInput().getBytes()[getTempInput().length()-1]);
    }

    public void inputTextarea1_processValueChange(ValueChangeEvent vce) {
    }

    public void inputTextarea2_processValueChange(ValueChangeEvent vce) {
    }

    public String button2_action() {
        //return null means stay on the same page

        return null;
    }

    public void menuItem4_processAction(ActionEvent ae) {

        auth a = (auth) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(FacesContext.getCurrentInstance().getELContext(), null, "auth");
        newProject.setUserName(a.getVisit().getUser());
        panelPopup2Bean.setShowDraggablePanel(true);
    }

    public String menuItem4_action() {
        //return null means stay on the same page
        return "NewProject";
    }

    public String menuItem5_action() {
        //return null means stay on the same page
        return null;
    }

    public void button3_processAction(ActionEvent ae) {
        //DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        //dateFormat.format(date);
        newProject.setCreated(date);
        newProject.setModified(date);
        newProject.setId(projectsFacade.getProjectsCount() + 1);
        try {
            projectsFacade.create(newProject);
        } catch (PreexistingEntityException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RollbackFailureException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setCurrentProject(projectsFacade.findProjects(projectsFacade.getProjectsCount()));
        panelPopup2Bean.setShowDraggablePanel(false);
    }

    public void menuItem5_processAction(ActionEvent ae) {
        //auth a = (auth) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(FacesContext.getCurrentInstance().getELContext(), null, "auth");
        // newFile.setUserName(a.getVisit().getUser());
        newFile.setProjectId(currentProject);
        newFile.setContents("");

        panelPopup1Bean.setShowDraggablePanel(true);
    }

    public void button2_processAction(ActionEvent ae) {
        Date d = new Date();
        newFile.setCreated(d);
        newFile.setModified(d);
        newFile.setId(filesFacade.getFilesCount() + 1);
        // newFile.setProjectId(currentProject);
        try {
            filesFacade.create(newFile);
        } catch (PreexistingEntityException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RollbackFailureException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setCurrentFile(filesFacade.findFiles(filesFacade.getFilesCount()));
        panelPopup1Bean.setShowDraggablePanel(false);
    }

    public void menuItem6_processAction(ActionEvent ae) {
        //projectsFacade.findProjects(__placeholder)
        panelPopup3Bean.setShowDraggablePanel(true);
    }

    public void open_project() {
        // currentProject = (Projects) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentProjects", new ProjectsConverter(), null);
        String theId = JsfUtil.getRequestParameter("jsfcrud.currentProjects");
        setCurrentProject(projectsFacade.findProjects(Integer.parseInt(theId)));
        setCurrentFile(null);
        panelPopup3Bean.setShowDraggablePanel(false);
    }

    public void open_file() {
        String theId = JsfUtil.getRequestParameter("jsfcrud.currentFiles");
        setCurrentFile(filesFacade.findFiles(Integer.parseInt(theId)));
        panelPopup4Bean.setShowDraggablePanel(false);
    }

    public void menuItem7_processAction(ActionEvent ae) {
        panelPopup4Bean.setShowDraggablePanel(true);
    }

    public void menuItem8_processAction(ActionEvent ae) {
        try {
            filesFacade.edit(currentFile);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RollbackFailureException ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ide.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void button4_processAction(ActionEvent ae) {
        String s = getTempInput();
        if (s.endsWith("\n")) {
            setInput(s);
            if (p != null) {
            }
        }
    }
}

